package vrp;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import vrp.SOrder;
import vrp.Customer;
import vrp.PMF;

public class SOrderItemEditServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {

    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	DateFormat df = new SimpleDateFormat ("yyyy-MM-dd");
        
    	long sorderID = Integer.parseInt(req.getParameter("sorder"));
    	long sorderItemID = Integer.parseInt(req.getParameter("sorderItem"));
    	long productID = Integer.parseInt(req.getParameter("product"));
    	int quantity = Integer.parseInt(req.getParameter("quantity"));
    	int sorderItemStatus = Integer.parseInt(req.getParameter("sorderItemStatus"));
    	
        try {
        	Date deliveryDate = df.parse(req.getParameter("deliveryDate"));

        	Key sorderKey = KeyFactory.createKey(SOrder.class.getSimpleName(), sorderID);
            SOrder sorder = pm.getObjectById(SOrder.class, sorderKey);
            SOrderItem sorderItem = null;
            for (SOrderItem oi : sorder.getSOrderItems()) {
            	if (oi.getKey().getId() == sorderItemID) {
            		sorderItem = oi;
            		break;
            	}
            }
                                	
            Key productKey = KeyFactory.createKey(Product.class.getSimpleName(), productID);
            //Product product = pm.getObjectById(Product.class, productKey);
            
            sorderItem.setProduct(productKey);
            sorderItem.setQuantity(quantity);
            sorderItem.setDeliveryDate(deliveryDate);
            sorderItem.setSOrderItemStatus(sorderItemStatus);
            
            pm.makePersistent(sorder);
        } catch (ParseException e) {
			e.printStackTrace();
		} finally {
            pm.close();
        }
        resp.sendRedirect("/sorderitems.jsp?sorder=" + sorderID);
    }
}